package by.grsu.shakh.dao;

import java.io.Serializable;
import java.util.List;

import by.grsu.shakh.entity.BookItem;
import by.grsu.shakh.table.BookItemTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class BookItemDao extends AbstractDao<BookItemTable, BookItem> {

	public BookItemDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(BookItem newBook) {
		newBook.setId(getNextId());
		final BookItemTable bookItemTable = deserializeFromXml();
		bookItemTable.getRows().add(newBook);
		serializeToXml(bookItemTable);

	}

	@Override
	public void update(BookItem entity) {
		final BookItemTable bookItemTable = deserializeFromXml();
		for (BookItem b : bookItemTable.getRows()) {
			if (b.getId().equals(entity.getId())) {
				b.setOrderType(entity.getOrderType());
				b.setOwnerId(entity.getOwnerId());
				b.setBookid(entity.getBookid());
			}
		}
		serializeToXml(bookItemTable);
	}

	@Override
	public BookItem get(Serializable id) {
		final BookItemTable bookItemTable = deserializeFromXml();
		for (BookItem b : bookItemTable.getRows()) {
			if (b.getId().equals(id)) {
				return b;
			}
		}
		return null;
	}

	@Override
	public List<BookItem> getAll() {
		BookItemTable bookItemTable = deserializeFromXml();
		return bookItemTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final BookItemTable bookItemTable = deserializeFromXml();
		BookItem toBeDeletedBook = null;
		for (BookItem b : bookItemTable.getRows()) {
			if (b.getId().equals(id)) {
				toBeDeletedBook = b;
			}
		}
		bookItemTable.getRows().remove(toBeDeletedBook);
		serializeToXml(bookItemTable);
	}

	@Override
	protected Class<BookItemTable> getTableClass() {
		return BookItemTable.class;
	}

}
